package dreampack.dataQuery;

import java.sql.*;

import dreampack.*;
import dreampack.dataType.*;

public class UserQuery {
	public UserQuery() { }
	
	public static UserType queryById(DreamDB dreamDb, int userId) throws Exception{
		UserType user = null;
		Connection con = null;
		PreparedStatement prepStmt = null;
		ResultSet rs = null;
		
		try{
			con = dreamDb.getConnection();
			String selectStatement = "select * from t_user where id=?";
			prepStmt = con.prepareStatement(selectStatement);
			prepStmt.setInt(1, userId);
			rs = prepStmt.executeQuery();
			if (rs.next()) {
				user = new UserType();
				user.init(dreamDb, rs);
				return user;
			}
			else
				return null;
		}finally{
			dreamDb.closeResultSet(rs);
			dreamDb.closeStatement(prepStmt);
			dreamDb.closeConnection(con);
		}
	}
	
	public static UserType queryByName(DreamDB dreamDb, String userName) throws Exception{
		UserType user = null;
		Connection con = null;
		PreparedStatement prepStmt = null;
		ResultSet rs = null;
		
		try{
			con = dreamDb.getConnection();
			String selectStatement = "select * from t_user where name=?";
			prepStmt = con.prepareStatement(selectStatement);
			prepStmt.setString(1, userName);
			rs = prepStmt.executeQuery();
			if (rs.next()) {
				user = new UserType();
				user.init(dreamDb, rs);
				return user;
			}
			else
				return null;
		}finally{
			dreamDb.closeResultSet(rs);
			dreamDb.closeStatement(prepStmt);
			dreamDb.closeConnection(con);
		}
	}
	
	public static UserType checkUser(DreamDB dreamDb, String userName, String userPwd) throws Exception{
		Connection con = null;
		PreparedStatement prepStmt = null;
		ResultSet rs = null;
		try{
			con = dreamDb.getConnection();
			String searchStatement = "select * from t_user where name=? and password=?";
			prepStmt = con.prepareStatement(searchStatement);
			prepStmt.setString(1, userName);
			prepStmt.setString(2, userPwd);
			rs = prepStmt.executeQuery();
			if (rs.next()){
				UserType user = new UserType();
				user.init(dreamDb, rs);
				return user;
			}
			else{
				return null;
			}
		} catch (Exception e) {
			return null;
		} finally{
			dreamDb.closeResultSet(rs);
			dreamDb.closeStatement(prepStmt);
			dreamDb.closeConnection(con);
		}
	}	

}
